package com.gp.study.tomcat.http;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MemoryAttribute;

public class GPHttpServletRequest {
	
	private String method;
	private String URL;
	private ChannelHandlerContext ctx;
	private HttpRequest req;
	
	public GPHttpServletRequest(ChannelHandlerContext ctx, HttpRequest req) {
		this.ctx = ctx;
		this.req = req;
	}
	public String getMethod() {
		return req.getMethod().name();
	}
	public String getURL() {
		return req.getUri();
	}

//	public Object[] getParams() {
//		ByteBuf content = req.content();
//		byte[] reqByte = new byte[content.readableBytes()];
//		content.readBytes(reqByte);
//		System.out.println("收到的请求参数："+new String(reqByte));
//		return params;
//	}

	public Map<String,String> getParameters() {
		Map<String, String>requestParams=new HashMap<String, String>();
		if(HttpMethod.GET == req.method()){
			QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
			Map<String, List<String>> parameters = decoder.parameters();
			for(Map.Entry<String,List<String>> entry:parameters.entrySet()){
				requestParams.put(entry.getKey(),entry.getValue().get(0));
			}

//			return parameters;


		}else if(HttpMethod.POST == req.method()){
			HttpPostRequestDecoder requestDecoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);
			List<InterfaceHttpData> bodyHttpDatas = requestDecoder.getBodyHttpDatas();
			for(InterfaceHttpData data:bodyHttpDatas){
				if(data.getHttpDataType() == InterfaceHttpData.HttpDataType
						.Attribute){
					MemoryAttribute attribute = (MemoryAttribute)data;
					requestParams.put(attribute.getName(),attribute.getValue());
				}
			}
		}
		return requestParams;
	}

	public String getParameter(String name) {
		Map<String,String> params = getParameters();
		return params.get(name);
//		List<String> param = params.get(name);
//		if (null == param) {
//			return null;
//		} else {
//			return param.get(0);
//		}
	}
	
}
